package org.jaaksi.kottlindemo.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import libcore.eventbus2.registerEvent
import org.jaaksi.kottlindemo.LibConfig
import org.jaaksi.kottlindemo.R
import org.jaaksi.kottlindemo.databinding.FragmentCalcuatorBinding
import org.jaaksi.kottlindemo.ui.SecondActivity
import org.jaaksi.kottlindemo.util.SoftInputHelper
import org.jetbrains.anko.startActivity
import timber.log.Timber

class CalculatorFragment : Fragment() {
    private lateinit var binding: FragmentCalcuatorBinding
    private val homeViewModel by activityViewModels<HomeViewModel>()
    private var msgId = 0L

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentCalcuatorBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onSaveInstanceState(outState: Bundle) {
        outState.putLong("msgId", msgId)
        super.onSaveInstanceState(outState)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        SoftInputHelper(requireActivity().window.decorView) {
            val toast = "键盘 ${if (it) "弹出" else "收起"}"
            println(">> $toast")
        }.also {
            lifecycle.addObserver(it)
        }

//        observeEvent<GlobalEvent> {
////            Toast.makeText(LibConfig.applicationContext, "收到Event", Toast.LENGTH_SHORT).show()
//        }

//        EventBus.register<GlobalEvent>(this){
//            Toast.makeText(LibConfig.applicationContext, "收到Event", Toast.LENGTH_SHORT).show()
//        }
        // 粘性事件作为EventBus会有坑，这个页面销毁后再进来又会收到。但非粘性的又无法解决dont keep activity的问题
        // 无返注销，页面销毁重建会再注册一次?,直接收到event？
        registerEvent<GlobalEvent>(savedInstanceState != null) {
            if (savedInstanceState?.getLong("msgId") == it.id) return@registerEvent

            msgId = it.id
            Toast.makeText(LibConfig.applicationContext, "收到Event", Toast.LENGTH_SHORT).show()
            Timber.e("收到Event1 ${it.id}")
            // 对于只需要响应一次的事件，比如收到之后弹一个dialog。dont keep activity会导致每次都可以收到。我们判断一下
        }

        // 要避免重复注册
//        registerEvent<GlobalEvent>(false) {
//            Toast.makeText(LibConfig.applicationContext, "收到Event", Toast.LENGTH_SHORT).show()
//            Timber.e("收到Event2")
//        }


        binding.btn.setOnClickListener {
            parentFragmentManager.setFragmentResult("toast2", bundleOf("id" to "111"))
            homeViewModel.changeTab(R.id.navigation_history)

        }

        binding.btn2.setOnClickListener {
//            postEvent(GlobalEvent())
            requireActivity().startActivity<SecondActivity>()
        }
    }

}